package com.intramirror.wd.service.security;

import com.intramirror.common.base.exception.ImBusinessException;
import com.intramirror.wd.business.manage.UserManage;
import com.intramirror.wd.business.util.SpringUtils;
import com.intramirror.wd.model.po.TransitUser;
import com.intramirror.wd.service.security.common.ErrorCode;
import com.intramirror.wd.service.security.config.TokenProperties;
import com.intramirror.wd.service.security.model.token.RawAccessToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.apache.commons.lang.StringUtils;
/**
 * Created by juzhongzheng on 2018/4/28.
 */
public class UserToken {
    private static UserManage userManage;
    private static TokenProperties tokenProperties;

    static  {
        if(userManage == null){
            userManage = (UserManage)SpringUtils.getBean(UserManage.class);
        }
        if(tokenProperties == null){
            tokenProperties = (TokenProperties) SpringUtils.getBean(TokenProperties.class);
        }
    }
    public static TransitUser getUserByToken(String token){
        //init();
        if (StringUtils.isBlank(token)) return null;
        RawAccessToken accessToken = new RawAccessToken(token);
        Jws<Claims> jwsClaims =  accessToken.parseClaims(tokenProperties.getSigningKey());
        String subject = jwsClaims.getBody().getSubject();
        if(StringUtils.isNotBlank(subject)) {
            TransitUser user = userManage.findUserByUserName(subject);
            return user;
        }else {
            throw new ImBusinessException(ErrorCode.AUTHENTICATION.toString(),"Authentication failed");
            //throw ErrorResponse.of("Authentication failed", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED);
        }
    }
}
